<template>
    <div class="admin-container">
        <el-form v-show="showSearch" ref="form" :model="searchForm" label-width="120px" size="small">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="任务名称:" prop="jobName" class="search-item">
                        <el-input v-model.trim="searchForm.jobName" placeholder="请输入" class="search-input" />
                    </el-form-item>
                    <el-form-item label="任务状态" prop="status" class="search-item">
                        <el-select v-model="searchForm.status" placeholder="任务状态" class="search-input" clearable
                            size="small" style="width: 250px">
                            <el-option v-for="dict in dict.type.sys_job_status" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label=" ">
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                        <el-button style="margin-left:20px" icon="el-icon-setting" @click="refresh">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPermi="['system:job:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
        </el-row>
        <el-table ref="multipleTable" v-loading="loading" border stripe :data="tableData">
            <el-table-column label="编号" type="index" width="50" align="center" />
            <el-table-column label="任务名称" prop="jobName" align="center" />
            <el-table-column label="Cron 表达式" prop="cronExpression" width="140" align="center" />
            <el-table-column label="任务状态" prop="status" align="center">
                <template slot-scope="scope">
                    <span class="green-txt" v-if="scope.row.status === 'W'">运行中</span>
                    <span class="red-txt" v-else>暂停</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="更新时间" prop="updateTime" width="160" align="center">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="400" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-hasPermi="['system:job:remove']" type="text" icon="el-icon-delete" @click="handleDel(scope.row)">删除</el-button>
                    <el-button v-hasPermi="['system:job:edit']" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button v-hasPermi="['system:job:run']" type="text" icon="el-icon-video-play" @click="handleRun(scope.row)">执行</el-button>
                    <el-button v-hasPermi="['system:job:log']" type="text" icon="el-icon-view" @click="handleViewJobLog(scope.row)">日志</el-button>
                    <el-button v-hasPermi="['system:job:pause']" type="text" icon="el-icon-video-pause" @click="handlePause(scope.row)">暂停</el-button>
                    <el-button v-hasPermi="['system:job:resume']" type="text" icon="el-icon-refresh" @click="handleResume(scope.row)">恢复</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="table-pagination">
            <el-pagination :current-page="pageNumber" :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin:20px"
                @size-change="onPageSizeChangeEvent" @current-change="onPageNumberChangeEvent" />
        </div>
        <el-drawer title="运行日志" :visible.sync="drawer" direction="rtl" size="50%">
            <el-table v-loading="jobLogloading" border stripe :data="jobLogTableData">
                <el-table-column label="执行时间" prop="executeTime" width="220" align="center" />
                <el-table-column label="结束时间" prop="endTime" width="220" align="center" />
                <el-table-column label="执行参数" prop="parameter" width="160" align="center" :show-overflow-tooltip="true" />
                <el-table-column label="执行状态" prop="status" align="center">
                    <template slot-scope="scope">
                        <span class="green-txt" v-if="scope.row.status === 'S'">正常</span>
                        <span class="red-txt" v-else>异常</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-drawer>
        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="任务名称" prop="jobName">
                            <el-input v-model.trim="form.jobName" class="search-input" placeholder="请输入任务名称" maxlength="30" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="定时策略" prop="cronExpression">
                            <el-input v-model.trim="form.cronExpression" class="search-input" placeholder="请输入定时策略" maxlength="50" show-word-limit @focus="showDialog" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="任务类名" prop="jobClassName">
                            <el-input v-model.trim="form.jobClassName" class="search-input input-width" placeholder="例：com.ithuameng.admin.job.test.TestJob" maxlength="255" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="任务参数" prop="parameter">
                            <el-input v-model.trim="form.parameter" class="search-input input-width" placeholder="例：a=5&b=2&c=0" maxlength="255" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="任务描述" prop="parameter">
                            <el-input v-model.trim="form.description" class="mult-text input-width" type="textarea" :rows="3" placeholder="请输入任务描述" maxlength="255" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="任务状态" prop="status">
                            <el-switch v-model="form.status" active-color="#13ce66" inactive-color="#ff4949" active-value="W" inactive-value="S" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- cron 配置 -->
        <el-dialog title="生成 cron" :visible.sync="showCron">
            <vcrontab @hide="showCron=false" @fill="crontabFill" :expression="expression"></vcrontab>
        </el-dialog>
    </div>
</template>
  
<script>
import { listJob, addJob, updateJob, runJob, delJob, pauseJob, resumeJob, getJobLog } from '@/api/system/job.js'
// 引入cron插件
import vcrontab from "vcrontab";

export default {
    name: 'Job',
    dicts: ['sys_job_status'],
    components: { vcrontab },
    data() {
        return {
            // 列表加载效果控制
            loading: false,
            // 搜索条件
            searchForm: {},
            // 当前页
            pageNumber: 1,
            // 每页数量
            pageSize: 10,
            // 总数量
            total: 0,
            // 表格数据
            tableData: [],
            // 抽屉控制
            drawer: false,
            // 任务日志加载效果控制
            jobLogloading: false,
            // 任务日志表格数据
            jobLogTableData: [],
            // 弹框标题
            title: '',
            // 弹框是否显示
            open: false,
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                jobName: [
                    { required: true, message: '任务名称不能为空', trigger: 'blur' }
                ],
                cronExpression: [
                    { required: true, message: '定时策略不能为空', trigger: 'blur' }
                ],
                jobClassName: [
                    { required: true, message: '任务类名称不能为空', trigger: 'blur' }
                ],
            },
            // Cron弹框表达式
            expression: "",
            // 显示Cron弹框
            showCron: false,
            // 显示搜索条件
            showSearch: true,
        }
    },
    mounted() {
        this.initUIData()
    },
    methods: {
        handleSearch() {
            this.pageNumber = 1
            this.pageSize = 10
            this.getList()
        },
        initUIData() {
            this.getList()
        },
        async getList() {
            const param = { ...this.searchForm }
            param.pageNumber = this.pageNumber
            param.pageSize = this.pageSize
            this.loading = true
            listJob(param).then(res => {
                // console.log(res.data);
                if (res.result) {
                    this.tableData = res.data.records
                    this.total = res.data.total
                    this.loading = false
                } else {
                    this.tableData = []
                    this.total = 0
                }
            })
        },
        switchChange (val) {
            if (val === 'N') {
                this.form.parameter = undefined
            }
        },
        onPageNumberChangeEvent(pageNumber) {
            this.pageNumber = pageNumber
            this.getList()
        },
        onPageSizeChangeEvent(pageSize) {
            this.pageSize = pageSize
            this.getList()
        },
        refresh() {
            this.pageNumber = 1
            this.pageSize = 10
            this.searchForm = {}
            this.getList()
        },
        crontabFill(value) {
            //确定后回传的值
            this.form.cronExpression = value;
        },
        showDialog() {
            this.expression = this.form.cronExpression;//传入的 cron 表达式，可以反解析到 UI 上
            this.showCron = true;
        },
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加用户'
        },
        handleEdit(row) {
            this.reset()
            this.form = {...row}
            this.open = true
            this.title = '修改用户'
        },
        /** 提交按钮 */
        submitForm: function () {
            const that = this
            that.$refs['form'].validate(valid => {
                if (valid) {
                    let param = {...that.form}
                    param.withParam = 'Y'
                    if (!param.parameter || param.parameter === '' || param.parameter === 'null') {
                        param.parameter = undefined
                        param.withParam = 'N'
                    }
                    if (that.form.id === undefined) {
                        addJob(param).then(res => {
                            if (res.result) {
                                this.getList()
                                this.open = false
                                this.$message.success(res.message)
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    } else {
                        updateJob(param).then(res => {
                            if (res.result) {
                                this.getList()
                                this.open = false
                                this.$message.success(res.message)
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    }
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                jobName: undefined,
                jobClassName: undefined,
                module: undefined,
                cronExpression: undefined,
                withParam: 'N',
                parameter: undefined,
                description: undefined,
                status: 'S'
            }
            this.resetForm('form')
        },
        handleDel(row) {
            this.$modal.confirm('是否确认删除定时任务"' + row.jobName + '"').then(function () {
                return delJob(row.id)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => { })
        },
        handleRun(row) {
            runJob({ id: row.id, parameter: row.parameter }).then((res) => {
                if (res.result) {
                    this.getList()
                    this.$message.success(res.message)
                }
            }).catch((res) => {
                this.$message.error(res.message)
            })
        },
        handlePause(row) {
            pauseJob(row.id).then(res => {
                if (res.result) {
                    this.getList()
                    this.$message.success(res.message)
                }
            }).catch((res) => {
                this.$message.error(res.message)
            })
        },
        handleResume(row) {
            resumeJob(row.id).then(res => {
                if (res.result) {
                    this.getList()
                    this.$message.success(res.message)
                }
            }).catch((res) => {
                this.$message.error(res.message)
            })
        },
        handleViewJobLog(row) {
            this.drawer = true
            this.jobLogloading = true
            getJobLog(row.id).then(res => {
                if (res.result) {
                    this.jobLogTableData = res.data
                    this.jobLogloading = false
                } else {
                    this.jobLogTableData = []
                }
            })
        }
    }
}
</script>
  
<style scoped>
.input-width {
    width: 610px;
}

.green-txt {
    font-weight: bold;
    color: #128b8e;
}

.red-txt {
    font-weight: bold;
    color: #feb64a;
}

.example {
    /* margin-left: 220px; */
    font-size: 25px;
    /* align-content: center; */
    color: #888;
}

.table-pagination {
    margin-top: 20px;
    text-align: right;
}

.search-label {
    width: 100px;
    text-align: right;
    padding-right: 10px;
    display: inline-block;
}

.search-col {
    margin: 10px 0;
}

.search-field {
    width: 180px;
}

.select-count {
    font-size: 13px;
    font-weight: 600;
    color: #40a9ff;
}

.select-clear {
    margin-left: 10px;
    color: #40a9ff;
}
</style>
